package cn.wenhaha.app.log;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
@Component
public class LogSocketHandler extends TextWebSocketHandler {

    private static   final  Map<String, WebSocketSession> mapToSession=new HashMap<>();


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        mapToSession.put(session.getId(),session);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        session.close();
        mapToSession.remove(session.getId());
    }

    public static void sendTextMessage(String text) {

        final Iterator<String> iterator = mapToSession.keySet().iterator();
        while (iterator.hasNext()){
            final WebSocketSession webSocketSession = mapToSession.get(iterator.next());
            try {
                webSocketSession.sendMessage(new TextMessage(text));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        mapToSession.remove(session.getId());
    }



   public static class  TextEvent  extends ApplicationEvent{

        public TextEvent(String source) {
            super(source);
        }

        public  String getText() {
            return  getSource().toString();
        }
    }



}
